package org.jinyan.wechat.service;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.jinyan.utils.CommonUtils;
import org.jinyan.wechat.controller.WechatMessageController;
import org.jinyan.wechat.model.WechatMessage;
import org.jinyan.wechat.model.WechatReply;
import org.jinyan.wechat.utils.WechatMessageUtil;

public class WechatService {

	private static Logger logger = Logger.getLogger(WechatService.class);

	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */
	public static String processRequest(HttpServletRequest request) {

		System.out.println("微信请求信息的处理 start");
		Map<String, String> requestMap = WechatMessageUtil
				.parseXmlToMap(request);
		WechatMessage message = WechatMessageUtil.mapToMessage(requestMap);
		message.setId(CommonUtils.getUUID());
		WechatMessageController controller = new WechatMessageController();
		try {
			controller.addMessage(message);//保存接受消息到数据库
		} catch (SQLException e) {
			logger.error("微信请求信息保存信息", e);
			e.printStackTrace();
		}
		
		String replyContent = WechatReply.WELCOME_CONTENT;
		String type = message.getMsgType();
		if (type.equals(WechatMessage.TEXT)) {// 仅处理文本回复内容
			replyContent = new ProcessMessageService().processMsgText(message);
		}
		// 拼装回复消息
		WechatReply reply = new WechatReply();
		reply.setToUserName(message.getFromUserName());
		reply.setFromUserName(message.getToUserName());
		reply.setCreateTime(new SimpleDateFormat("yyyyMMddhhmmss")
				.format(new Date()));
		reply.setMsgType(WechatReply.TEXT);
		reply.setContent(replyContent);
		// weixinService.addReply(reply);//保存回复消息到数据库
		// 将回复消息序列化为xml形式
		String back = WechatMessageUtil.replyToXml(reply);
		System.out.println(back);
		System.out.println("微信请求信息的处理 end ");
		return back;
	}

}
